package com.utility.project.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utility.project.common.base.ServiceException;
import com.utility.project.common.constants.YsConstant;
import com.utility.project.entity.YsCustomer;
import com.utility.project.entity.YsMemberConfig;
import com.utility.project.entity.YsOrder;
import com.utility.project.mapper.YsOrderMapper;
import com.utility.project.param.CustomerParam;
import com.utility.project.param.OrderParam;
import com.utility.project.service.IYsCustomerService;
import com.utility.project.service.IYsMemberConfigService;
import com.utility.project.service.IYsOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author yangzhiguo
 * @date 2024-06-13
 * @description 订单表
 */
@Service
@Slf4j
public class YsOrderServiceImpl extends ServiceImpl<YsOrderMapper, YsOrder> implements IYsOrderService {

    @Resource
    private IYsCustomerService iYsCustomerService;

    @Resource
    private IYsMemberConfigService ysMemberConfigService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveOrder(OrderParam param) {
        String orderCode = param.getOrderCode();
        String username = param.getUsername();
        Integer orderType = param.getOrderType();
        YsOrder ysOrder = queryOrder(orderCode);
        if (ysOrder == null) {
            ysOrder = new YsOrder();
            YsCustomer ysCustomer = iYsCustomerService.queryYsCustomer(username);
            Assert.notNull(ysCustomer, "用户不存在");
            ysOrder.setPhone(ysCustomer.getPhoneNumber());
            ysOrder.setUserId(ysCustomer.getId());
            ysOrder.setRealname(ysCustomer.getNickName());
            ysOrder.setOrderType(orderType);
            ysOrder.setPayStatus(YsConstant.PAID_PENDING);
            Assert.notNull(orderType, "订单类型不能为空");
            YsMemberConfig ysMemberConfig = ysMemberConfigService.queryConfig(orderType.toString());
            Assert.notNull(ysMemberConfig, "会员类型不存在");
            ysOrder.setOrderName(ysMemberConfig.getRemark());
            ysOrder.setOrderAmount(ysMemberConfig.getPrice());
            ysOrder.setOrderCode(orderCode);
            ysOrder.setOutTradeNo(generateOutTradeNo(orderCode));
            ysOrder.setPayType(YsConstant.WEI_XIN);
            ysOrder.setCreateTime(new Date());
            ysOrder.setCreateBy("admin");
            return baseMapper.insert(ysOrder);
        }else{
            log.error("订单已存在,orderCode:{}", orderCode);
            throw new ServiceException("订单已存在");
        }
    }

    /**
     * 生成支付订单号
     */
    private String generateOutTradeNo(String orderCode) {
        return orderCode + RandomUtils.nextInt(1000, 9999);
    }

    /**
     * 更新会员信息
     */
    private void updateCustomerStatus(OrderParam param){
        CustomerParam customerParam = new CustomerParam();
        customerParam.setUsername(param.getUsername());
        customerParam.setMemberType(param.getOrderType().toString());
        iYsCustomerService.updateCustomerStatus(customerParam);
    }

    @Override
    public YsOrder queryOrder(String orderCode) {
        QueryWrapper<YsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_code", orderCode);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<YsOrder> queryByUsername(String username) {
        YsCustomer ysCustomer = iYsCustomerService.queryYsCustomer(username);
        Assert.notNull(ysCustomer, "用户不存在");
        QueryWrapper<YsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", ysCustomer.getId());
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Integer editOrderStatus(OrderParam param) {
        YsOrder ysOrder = queryOrder(param.getOrderCode());
        Assert.notNull(ysOrder, "订单不存在");
        String userId = ysOrder.getUserId();
        YsCustomer ysCustomer = iYsCustomerService.getById(userId);
        Assert.notNull(ysCustomer, "用户不存在");
        ysOrder.setPayTime(new Date());
        ysOrder.setPayStatus(YsConstant.PAID_SUCCESS);
        ysOrder.setUpdateBy("admin");
        ysOrder.setUpdateTime(new Date());
        param.setOrderType(ysOrder.getOrderType());
        param.setUsername(ysCustomer.getUsername());
        //订单支付成功后，更新用户信息
        updateCustomerStatus(param);
        return baseMapper.updateById(ysOrder);
    }
}
